package com.codeest.geeknews.ui.main.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.codeest.geeknews.R;
import com.codeest.geeknews.base.BaseFragment;
import com.codeest.geeknews.base.contract.main.DoubanContract;
import com.codeest.geeknews.media.music.IMediaPlaybackService;
import com.codeest.geeknews.media.music.MediaPlaybackService;
import com.codeest.geeknews.media.music.MusicUtils;
import com.codeest.geeknews.media.receiver.MediaButtonReceiver;
import com.codeest.geeknews.model.bean.DoubanChannelBean;
import com.codeest.geeknews.model.bean.DoubanChannelBean.GroupsBean;
import com.codeest.geeknews.model.bean.DoubanChannelBean.GroupsBean.ChlsBean;
import com.codeest.geeknews.model.bean.DoubanLyricBean;
import com.codeest.geeknews.model.bean.DoubanPlaylistBean;
import com.codeest.geeknews.model.bean.DoubanPlaylistBean.SongBean;
import com.codeest.geeknews.model.bean.MusicInfo;
import com.codeest.geeknews.presenter.main.DoubanPresenter;
import com.codeest.geeknews.ui.main.activity.MusicActivity;
import com.codeest.geeknews.ui.main.adapter.DoubanMusicListAdapter;
import com.codeest.geeknews.util.ImageUtil;
import com.codeest.geeknews.util.convert.BeanConvertor;
import com.codeest.geeknews.util.convert.FieldFilter;
import com.codeest.geeknews.util.notify.MusicNotifyManager;
import com.codeest.geeknews.util.notify.NotifyId;
import com.codeest.geeknews.widget.RotateableRoundImageView;
import com.codeest.geeknews.widget.discrete.ScaleTransformerExt;
import com.yarolegovich.discretescrollview.DiscreteScrollView;
import com.yarolegovich.discretescrollview.Orientation;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.wcy.lrcview.LrcView;


/**
 * 播放器Fragment
 * 启动Fragment——>屏幕锁屏——>屏幕解锁——>切换到其他的Fragment——>回到桌面——>回到应用——>退出Fragment
 * (1)、启动Fragment
 * onAttach()->onCreate()->onCreateView()->onActivityCreated()->onStart()->onResume()
 * (2)、屏幕锁屏
 * onPause()->onStop()
 * (3)、屏幕解锁
 * onStart()->onResume()
 * (4)、切换Fragment
 * onPause()->onStop()->onDestroyView()
 * (5)、返回原先的Fragment
 * onCreateView->onActivityCreated()->onStart()->onResume()
 * (6)、回到桌面
 * onPause()->onSaveInstanceState()->onStop()
 * (7)、回到Activity
 * onStart()->onResume()
 * (8)、退出Fragment
 * onPause()->onStop()->onDestroyView()->onDestroy()->onDetach()
 * <p>
 * 显示歌词：http://www.jianshu.com/p/0feb6171b0c5
 */
public class DoubanMusicFragment extends BaseFragment<DoubanPresenter> implements DiscreteScrollView.OnItemChangedListener<RecyclerView.ViewHolder>,
        ServiceConnection, DoubanMusicListAdapter.OnMusicInfoListener, DoubanContract.ViewExt {

    private final static String TAG = "DoubanMusicFragment";

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.list)
    DiscreteScrollView mRecyclerView;
    @BindView(R.id.bgImage)
    ImageView bgImage;
    @BindView(R.id.btn_pause)
    ImageButton btn_pause;
    @BindView(R.id.position_text)
    TextView mCurrentTime;
    @BindView(R.id.duration_text)
    TextView mTotalTime;
    @BindView(R.id.seek_bar)
    ProgressBar mProgress;
    @BindView(R.id.lrcview)
    LrcView mLrcview;
    @BindView(R.id.musicBody)
    View musicBody;

    //private MusicInteraction mListener;
    private long[] list;
    private IMediaPlaybackService mService = null;
    private MusicUtils.ServiceToken mToken;
    private int mCurrentPosition = -1;


    private static final int REFRESH = 1;
    private static final int QUIT = 2;


    private long mPosOverride = -1;
    private boolean mFromTouch = false;
    private long mLastSeekEventTime;
    private long mDuration;
    private int seekmethod;
    private boolean paused;
    private boolean isBackground;
    private List<SongBean> mDatas;
    private DoubanMusicListAdapter mAdapter;
    private boolean isServiceHadBinded;
    private List<ChlsBean> mChanels;
    private String mSelectedChannelId;

    //TODO 添加通知栏提示
    private MusicNotifyManager mNotifyManager;
    private MusicInfo mMusicInfo;
    BeanConvertor conver = new BeanConvertor();
    //更新界面
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH://这里还可以在优化，退到后台一直更新通知但是不更新界面
                    refreshNotify();
                    long next = refreshNow();
                    queueNextRefresh(next);
                    break;

                case QUIT:
                    // This can be moved back to onCreate once the bug that prevents
                    // Dialogs from being started from onCreate/onResume is fixed.
                    new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.service_start_error_title)
                            .setMessage(R.string.service_start_error_msg)
                            .setPositiveButton(android.R.string.ok,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int whichButton) {
                                            //finish();
                                        }
                                    })
                            .setCancelable(false)
                            .show();
                    break;

                default:
                    break;
            }
        }
    };
    //播放状态监听
    private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(MediaPlaybackService.META_CHANGED)) {
                // redraw the artist/title info and
                // set new max for progress bar
                updateTrackInfo();
                setSeekControls();
                setPauseButtonImage();
                queueNextRefresh(1);
                setPager();
                updateExtra();
            } else if (action.equals(MediaPlaybackService.PLAYSTATE_CHANGED)) {
                setPauseButtonImage();
            } else if (action.equals(MediaPlaybackService.META_END)) {
                if (!TextUtils.isEmpty(mSelectedChannelId)) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mPresenter.getPlaylist(mSelectedChannelId);
                        }
                    }, 1000);//延迟1m, 平缓过渡

                }
            }
        }
    };

    //进度条监听
    private SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
        public void onStartTrackingTouch(SeekBar bar) {
            mLastSeekEventTime = 0;
            mFromTouch = true;
        }

        public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
            if (!fromuser || (mService == null)) return;
            long now = SystemClock.elapsedRealtime();
            if ((now - mLastSeekEventTime) > 250) {
                mLastSeekEventTime = now;
                mPosOverride = mDuration * progress / 1000;
                try {
                    mService.seek(mPosOverride);
                } catch (RemoteException ex) {
                    ex.printStackTrace();
                }
                // trackball event, allow progress updates
                if (!mFromTouch) {
                    refreshNow();
                    mPosOverride = -1;
                }
                mLrcview.onDrag(progress);
            }
        }

        public void onStopTrackingTouch(SeekBar bar) {
            mPosOverride = -1;
            mFromTouch = false;
        }
    };

    // 监听通知栏广播
    private BroadcastReceiver notificationReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (MusicNotifyManager.ACTION_PAUSE_NOTICE.equals(action)) {
                pauseOrPlay();
            }
        }

    };

    // 监听耳机拔除
    // 对于有线耳机，监听Intent.ACTION_HEADSET_PLUG系统广播，对于蓝牙耳机，监听BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED系统广播
    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(action)) {
                Log.i(TAG, "耳机插入");
            } else if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                if (BluetoothProfile.STATE_DISCONNECTED == adapter.getProfileConnectionState(BluetoothProfile.HEADSET)) {
                    //Bluetooth headset is now disconnected
                    //handleHeadsetDisconnected();
                    Log.i(TAG, "耳机插入");
                }
            } else if ("android.intent.action.HEADSET_PLUG".equals(action)) {
                if (intent.hasExtra("state")) {
                    if (intent.getIntExtra("state", 0) == 0) {
                        //handleHeadsetDisconnected();
                        Log.i(TAG, "耳机拔出");
                    }
                }
            }
        }

    };
    //SongBean 转成 MusicInfo
    private FieldFilter fieldFilter = new FieldFilter() {
        @Override
        public String[] fromFields() {
            return new String[]{"url", "picture", "artist", "title", "album", "length"};
        }

        @Override
        public String[] toFields() {
            return new String[]{"url", "picture", "artist", "title", "album", "duration"};
        }
    };

    @OnClick(R.id.btn_pause)
    public void onPauseClick() {
        pauseOrPlay();
    }


    @OnClick(R.id.btn_pre)
    public void onPreClick() {
        if (mRecyclerView.getCurrentItem() > 0) {//防止越界
            mRecyclerView.smoothScrollToPosition(mRecyclerView.getCurrentItem() - 1);
        }
    }


    @OnClick(R.id.btn_next)
    public void onNextClick() {
        if (mRecyclerView.getCurrentItem() < mDatas.size() - 1) {//防止越界
            mRecyclerView.smoothScrollToPosition(mRecyclerView.getCurrentItem() + 1);
        }
    }

    //暂停或播放，同时更新通知栏按钮状态
    private void pauseOrPlay() {
        try {
            if (mService.isPlaying()) {
                mService.pause();
            } else {
                mService.play();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void next() {
        try {
            mService.next();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void pre() {
        try {
            mService.prev();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_music;
    }

    @Override
    protected void initEventAndData() {
        setHasOptionsMenu(true);//给toolbar设置menu，否则不会调用onCreateOptionsMenu
        //
        mPresenter.getChannels();
        mDatas = new ArrayList<>();
        //
        mRecyclerView.addOnItemChangedListener(this);
        mRecyclerView.setOrientation(Orientation.HORIZONTAL);
        mAdapter = new DoubanMusicListAdapter(mDatas, this);//无循环Adapter
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setItemTransformer(new ScaleTransformerExt.Builder()
                .setMinScale(0.5f)
                .build());
        //注册播放状态监听器
        registerStatusListener();
        //注册耳机插拔监听
        registerMediaButtonListener();
        //注册广播监听
        registerNotificationListener();
        //
        mToken = MusicUtils.bindToService(mActivity, this);
        //
        mProgress.setMax(1000);
        if (mProgress instanceof SeekBar) {
            SeekBar seeker = (SeekBar) mProgress;
            seeker.setOnSeekBarChangeListener(mSeekListener);
        }

        musicBody.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mLrcview.getAlpha() == 0) {
                    mLrcview.animate().alpha(1);
                    mRecyclerView.animate().alpha(0);
                } else {
                    mLrcview.animate().alpha(0);
                    mRecyclerView.animate().alpha(1);
                }
            }
        });

        //通知
        if (mNotifyManager == null) {
            mNotifyManager = new MusicNotifyManager(mActivity);
        }
    }

    /**
     * 注册播放状态监听器
     */
    private void registerStatusListener() {
        IntentFilter f = new IntentFilter();
        f.addAction(MediaPlaybackService.PLAYSTATE_CHANGED);
        f.addAction(MediaPlaybackService.META_CHANGED);
        f.addAction(MediaPlaybackService.META_END);
        mActivity.registerReceiver(mStatusListener, new IntentFilter(f));
    }


    /**
     * 注册通知栏广播接收器
     */
    private void registerNotificationListener() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MusicNotifyManager.ACTION_PAUSE_NOTICE);//暂停动作
        mActivity.registerReceiver(notificationReceiver, intentFilter);
    }

    /**
     * 注册耳机插拔监听
     */
    private void registerMediaButtonListener() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);//为当拔出有线耳机时，播放器不会马上暂停，要等上一秒钟
        intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);//监听Android的系统广播AudioManager.ACTION_AUDIO_BECOMING_NOISY,但是这个广播只是针对有线耳机，或者无线耳机的手机断开连接的事件，监听不到有线耳机和蓝牙耳机的接入，监听这个广播就没有延迟了，UI可以立即响应
        mActivity.registerReceiver(headsetPlugReceiver, intentFilter);
        // for bluetooth headset connection receiver
        IntentFilter bluetoothFilter = new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        mActivity.registerReceiver(headsetPlugReceiver, bluetoothFilter);
        //
        //获得AudioManager对象
        AudioManager mAudioManager = (AudioManager) mActivity.getSystemService(Context.AUDIO_SERVICE);
        //构造一个ComponentName，指向MediaoButtonReceiver类
        ComponentName mComponent = new ComponentName(mActivity.getPackageName(), MediaButtonReceiver.class.getName());
        //注册一个MediaButtonReceiver广播监听
        mAudioManager.registerMediaButtonEventReceiver(mComponent);
        //注销方法
        //mAudioManager.unregisterMediaButtonEventReceiver(mComponent);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setToolBar(mToolbar, "");
    }


    @Override
    public void onAttach(Activity context) {
        super.onAttach(context);
    }

    //http://m.blog.csdn.net/u010290494/article/details/43836145
    @Override
    public void onStart() {
        super.onStart();
        mNotifyManager.remove(NotifyId.ID_MUSIC);
        //paused = false;
        isBackground = false;
        //mToken = MusicUtils.bindToService(mActivity, this);
        if (mToken == null) {
            // something went wrong
            mHandler.sendEmptyMessage(QUIT);
        }
        //registerStatusListener();
        updateTrackInfo();
        //每隔next毫秒检查一次更新
        long next = refreshNow();
        queueNextRefresh(next);
        refreshNotify();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateTrackInfo();
        setPauseButtonImage();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mPreImageView != null) {
            mPreImageView.stopRotation();
        }
    }

    @Override
    public void onStop() {
        isBackground = true;
        mNotifyManager.showNotification(NotifyId.ID_MUSIC, mMusicInfo);
//        paused = true;
//        mHandler.removeMessages(REFRESH);
//        mActivity.unregisterReceiver(mStatusListener);
//        MusicUtils.unbindFromService(mToken);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mActivity.unregisterReceiver(headsetPlugReceiver);
        mActivity.unregisterReceiver(notificationReceiver);
        mHandler.removeMessages(REFRESH);
        mActivity.unregisterReceiver(mStatusListener);
        MusicUtils.unbindFromService(mToken);
        try {
            mService.stop();
            mService = null;
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.music_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_music_more:
                if (mChanels != null) {
                    DoubanChannelFragment bottomSheetDialogFragment = new DoubanChannelFragment.Builder(getActivity())
                            .setOnItemSelectedListener(new DoubanChannelFragment.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(View view, int position) {
                                    int selectedId = mChanels.get(position).getId();
                                    mSelectedChannelId = String.valueOf(selectedId);
                                    mPresenter.getPlaylist(mSelectedChannelId);
                                }
                            })
                            .setData(mChanels)
                            .setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2)
                            .create();
                    bottomSheetDialogFragment.show(getChildFragmentManager());
                }
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 之所以不直接设置icon(mToolbar.setNavigationIcon(R.drawable.icon_toolbar_back);)是为了使用系统默认的
     *
     * @param toolbar
     * @param title
     */
    protected void setToolBar(Toolbar toolbar, String title) {
        toolbar.setBackgroundResource(android.R.color.transparent);
        //状态栏透明和间距处理
        {
            //StatusBarUtil.setPaddingSmart(mActivity, mToolbar);
        }
        TextView titleView = ((TextView) toolbar.findViewById(R.id.title));
        if (titleView != null) {
            titleView.setText(title);
            toolbar.setTitle("");
        } else {
            toolbar.setTitle(title);
        }
        ((AppCompatActivity) mActivity).setSupportActionBar(toolbar);
        ((AppCompatActivity) mActivity).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ((AppCompatActivity) mActivity).getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MusicActivity.isMusicActivityTop = false;
                try {
                    if (mService != null && mService.isPlaying()) {
                        mService.pause();//先暂停播放，似的首页收到暂停通知停止播放按钮的动画
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                mActivity.finish();
                mActivity.overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
                //mActivity.overridePendingTransition(R.anim.slide_top_in, R.anim.slide_bottom_out);
            }
        });
    }


    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mService = IMediaPlaybackService.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }


    private void queueNextRefresh(long delay) {
        if (!paused) {
            Message msg = mHandler.obtainMessage(REFRESH);
            mHandler.removeMessages(REFRESH);
            mHandler.sendMessageDelayed(msg, delay);
        }
    }

    /**
     * 更新界面（进度条）
     *
     * @return
     */
    private long refreshNow() {
        if (mService == null)
            return 500;
        try {
            long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
            if ((pos >= 0)) {
                mCurrentTime.setText(MusicUtils.makeTimeString(mActivity, pos / 1000));
                if (mDuration > 0) {
                    mProgress.setProgress((int) (1000 * pos / mDuration));
                    mLrcview.updateTime((int) (pos));
                } else {
                    mProgress.setProgress(0);
                }
            } else {
                mCurrentTime.setText("0:00");
                mProgress.setProgress(0);
            }
            // calculate the number of milliseconds until the next full second, so
            // the counter can be updated at just the right time
            long remaining = 1000 - (pos % 1000);

            // approximate how often we would need to refresh the slider to
            // move it smoothly
            int width = mProgress.getWidth();
            if (width == 0) width = 320;
            long smoothrefreshtime = mDuration / width;

            if (smoothrefreshtime > remaining) return remaining;
            if (smoothrefreshtime < 20) return 20;
            return smoothrefreshtime;
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
        return 500;
    }

    /**
     * 更新通知栏按钮（ 退到后台再更新，否则会造成界面卡顿）
     */
    private void refreshNotifyPause() {
        if (!isBackground) {
            return;
        }
        if (mService != null) {
            try {
                mNotifyManager.updatePlayButton(NotifyId.ID_MUSIC, mService.isPlaying());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 更新通知栏（ 退到后台再更新，否则会造成界面卡顿）
     */
    private void refreshNotify() {
        if (!isBackground) {
            return;
        }
        if (mService == null || mMusicInfo == null)
            return;
        //mNotifyManager.showNotification(NotifyId.ID_MUSIC, mMusicInfo);
        try {
            mMusicInfo.setDuration(mService.duration());
            long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
            if ((pos >= 0)) {
                if (mDuration > 0) {
                    mMusicInfo.setProgress(pos);
                } else {
                    mMusicInfo.setProgress(0);
                }
            } else {
                mMusicInfo.setProgress(0);
            }
            mNotifyManager.updateProgress(NotifyId.ID_MUSIC, mMusicInfo);
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
    }

    private void updateExtra() {
    }

    private void updateTrackInfo() {
        if (mService == null) {
            return;
        }
        try {
            mDuration = mService.duration();
            mTotalTime.setText(MusicUtils.makeTimeString(mActivity, mDuration / 1000));
        } catch (RemoteException ex) {
            //finish();
        }
    }

    private void setSeekControls() {
        if (mService == null) {
            return;
        }

        try {
            if (mService.duration() > 0) {
                mProgress.setEnabled(true);
            } else {
                mProgress.setEnabled(false);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    private void setPauseButtonImage() {
        try {
            if (mService != null && mService.isPlaying()) {//播放状态
                btn_pause.setImageResource(R.drawable.selector_player_btn_pause);//
                if (mPreImageView != null) {
                    mPreImageView.startRotation();//旋转
                }
            } else {
                btn_pause.setImageResource(R.drawable.selector_player_btn_play);
                if (mPreImageView != null) {
                    mPreImageView.stopRotation();
                }
            }
            refreshNotifyPause();

        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
    }


    /**
     * 播放下一首
     */
    private void setPager() {
        if (mService == null) {
            return;
        }
        try {
            int position = mService.getQueuePosition() + 1;
            //mPager.setCurrentItem(position, false);//切换下一页

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private RotateableRoundImageView mPreImageView;

    @Override
    public void onCurrentItemChanged(@Nullable RecyclerView.ViewHolder viewHolder, int adapterPosition) {
        if (viewHolder != null) {
            RotateableRoundImageView imageView = (RotateableRoundImageView) viewHolder.itemView.findViewById(R.id.image);
            if (mCurrentPosition != adapterPosition) {
                if (mCurrentPosition < adapterPosition) {
                    next();
                } else {
                    pre();
                }
                Drawable _old = new BitmapDrawable(ImageUtil.getBitmapFromDrawable(bgImage.getDrawable()));
                Bitmap bitmap = ImageUtil.getBitmapFromDrawable(imageView.getDrawable());
                Drawable _new;
                if (bitmap == null) {
                    _new = new ColorDrawable(getResources().getColor(android.R.color.black));
                } else {
                    _new = new BitmapDrawable(bitmap);
                }
                //背景图片渐变
                alphaBackground(_old, _new);
                //设置标题
                setToolBar(mToolbar, (String) imageView.getTag(R.id.tag_title) + "(" + (String) imageView.getTag(R.id.tag_artist) + ")");
                //旋转
                //imageView.startRotation();
                //mPreImageView = imageView;
                //mPreImageView.startRotation();
                mCurrentPosition = adapterPosition;
                //
                SongBean currentSong = mDatas.get(mCurrentPosition);
                mMusicInfo = conver.convert(currentSong, MusicInfo.class, fieldFilter);
            }
            //旋转
            if (mPreImageView != null) {
                mPreImageView.stopRotation();
            }
            mPreImageView = imageView;
            mPreImageView.startRotation();

        }

    }

    /**
     * 背景图片渐变
     */
    private void alphaBackground(Drawable _old, Drawable _new) {
        if (_old == null) {
            bgImage.setImageDrawable(_new);
        } else {
            //渐变切换
            TransitionDrawable td = new TransitionDrawable(new Drawable[]{_old, _new});
            bgImage.setImageDrawable(td);
            td.startTransition(300);
        }
    }

    @Override
    public void onImageLoaded(RecyclerView.ViewHolder holder, int position, String url) {
        if (mCurrentPosition == position) {
            Glide.with(this)
                    .load(url)
                    .into(bgImage);
        }

    }

    //频道加载完毕，通过频道id获取歌曲列表
    @Override
    public void channelsLoaded(DoubanChannelBean channels) {
        try {
            //默认加载第一个频道的歌曲
            int defaultid = channels.getGroups().get(0).getChls().get(0).getId();
            mSelectedChannelId = String.valueOf(defaultid);
            mPresenter.getPlaylist(mSelectedChannelId);
            mChanels = new ArrayList<>();
            List<GroupsBean> allChannel = channels.getGroups();
            for (GroupsBean item : allChannel) {
                mChanels.addAll(item.getChls());
            }
        } catch (NullPointerException e) {//
            e.printStackTrace();
        }

    }

    //通过channelid 获取到歌曲列表
    @Override
    public void playlistLoaded(DoubanPlaylistBean playlist) {
        mDatas.clear();
        ArrayList<String> urls = new ArrayList<>();
        List<SongBean> songs = playlist.getSong();
        for (SongBean song : songs) {
            urls.add(song.getUrl());
            mDatas.add(song);
        }
        mAdapter.notifyDataSetChanged();
        long[] list = new long[urls.size()];
        for (int i = 0; i < urls.size(); i++) {
            list[i] = MusicUtils.insert(mActivity, urls.get(i));
        }

        //
        mCurrentPosition = 0;
        //
        SongBean currentSong = mDatas.get(0);
        mMusicInfo = conver.convert(currentSong, MusicInfo.class, fieldFilter);

        if (mService != null) {
            try {
                mService.open(list, mCurrentPosition);
                setToolBar(mToolbar, currentSong.getTitle() + "(" + currentSong.getArtist() + ")");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        if (mDatas != null && !mDatas.isEmpty()) {
            int sid = currentSong.getSid();
            String ssid = currentSong.getSsid();
            mPresenter.getLyric(sid, ssid);
        }

    }

    //获取到歌词
    @Override
    public void lyricLoaded(DoubanLyricBean playlist) {
        mLrcview.loadLrc(playlist.getLyric());
    }


    public interface MusicInteraction {
        void toggleMenu();
    }
}

